# -*- coding: utf-8 -*-
from flask_restful import abort
from functools import wraps
from app.api.services.service_user import ServiceUser
import re


def auth_token(request_):
	def decorator(f):
		@wraps(f)
		def decorated_function(*args, **kwargs):
			token = request_.args.get('token')
			if not token:
				abort(401, message="Need token and not empty")
			data = ServiceUser().auth_jwt_token(token)
			if data["errcode"] != 200:
				return data
			return f(*args, **kwargs)

		return decorated_function
	return decorator


def very_token(value, name):
	if value is None:
		raise ValueError("token is not null")
	data = ServiceUser().auth_jwt_token(value)
	if data["errcode"] != 200:
		abort(400, message=data)
	return data["data"]


def very_phone(value, name):
	tel = re.compile("^0\d{2,3}\d{7,8}$|^1[23589]\d{9}$|^147\d{8}")
	if tel.match(value) and len(value) > 7:
		return value
	else:
		print("====very_phone=======", value)
		print("====name=======", name)
		abort(400, message=u"您输入的号码有误！")


def ver_num(value, name):
	import re
	# return True if re.search("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$", value) and len(value) >= 8 else False
	if re.search("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$", value) and len(value) >= 8:
		return True
	else:
		raise ValueError("Password cannot be empty and at least eight characters")


def very_role(value, name):
	if value in ["", None]:
		raise ValueError("The {} cannot be empty".format(name))
	if value in ["admin", "expert", "normal"]:
		return value
	else:
		raise ValueError("The role you entered is incorrect")


def very_password(value, name):
	if value in ["", None]:
		raise ValueError("The {} cannot be empty".format(name))
	if re.search("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$", value) and len(value) < 8:
		raise ValueError("{} cannot be empty and at least 8 characters".format(name))
	return value
